package controllers

import java.nio.file.Files

import config.{Global, MyAwait, MyRow}
import dao.GenomeDao
import javax.inject.Inject
import play.api.libs.json.Json
import play.api.mvc.{AbstractController, ControllerComponents}
import utils.TableUtils.pageForm
import utils.{ExecCommand, TableUtils}

import scala.concurrent.ExecutionContext

class GenomeController @Inject()(genomeDao: GenomeDao,
                                 cc: ControllerComponents)
                                (implicit exec: ExecutionContext) extends AbstractController(cc) with MyAwait with MyRow {

  def genomePage(species:String) = Action { implicit request =>
    Ok(views.html.browse.genomePage(species))
  }

  def getGenomeData(species:String) = Action { implicit request =>
    val page = pageForm.bindFromRequest.get
    val data = TableUtils.genome(species)
    val orderX = TableUtils.dealMapDataByPage(data, page)
    val total = orderX.size
    val tmpX = orderX.slice(page.offset, page.offset + page.limit)
    Ok(Json.obj("rows" -> tmpX, "total" -> total))
  }

  def genePage(id: Int) = Action.async { implicit request =>
    genomeDao.getById(id).map { x =>
      Ok(views.html.browse.genePage(x))
    }
  }

  def genePageByGeneId(geneid: String) = Action.async { implicit request =>
    genomeDao.getByGeneId(geneid).map { x =>
      Ok(views.html.browse.genePage(x))
    }
  }

  def getSeqs(geneid: String, gos: String,species:String) = Action { implicit request =>
    val goData =gos.split(";").map{x=>
      Json.obj("name" -> x,"des" -> TableUtils.goMap(x))
    }

    val cds = s"${Global.samtools} faidx ${Global.path}/fasta/cds/$species.cds $geneid"
    val pep = s"${Global.samtools} faidx ${Global.path}/fasta/pep/$species.pep $geneid"
    val tmpDir = Files.createTempDirectory("tmpDir").toString
    val exec = new ExecCommand
    exec.exect(Array(cds, pep), tmpDir)
    Ok(
      if (exec.isSuccess) {
        val seq = exec.getOutStr.split(">")
        val cdsSeq = seq(1).split("\n").tail.mkString
        val pepSeq = seq.last.split("\n").tail.mkString
        Json.obj("cds" -> cdsSeq, "pep" -> pepSeq,"go" -> goData)
      } else {
        Json.obj("valid" -> "false", "msg" -> exec.getErrStr,"go" -> goData)
      })
  }


}
